var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
var { ConversationModel,LoginModel } = require('../model/model');

// 获取会话列表
router.get('/api/conversations', async (req, res) => {
    const data = await ConversationModel.find();
    res.send({
        code: 200,
        data: data
    });
});

// 发送消息
router.post('/api/conversations/sendMessage', async (req, res) => {
    try {
        const { conversationId, content, type } = req.body; // 添加 type 参数
        
        // 查找并更新会话
        const conversation = await ConversationModel.findOne({ conversationId });
        if (!conversation) {
            return res.status(404).send({
                code: 404,
                message: '会话不存在'
            });
        }

        // 创建新消息，使用传入的 type
        const newMessage = {
            content,
            type: type || 'service', // 如果没有传入 type，默认为 'service'
            timestamp: new Date()
        };

        // 添加消息到会话中
        conversation.messages.push(newMessage);
        await conversation.save();

        res.send({
            code: 200,
            data: newMessage,
            message: '发送成功'
        });
    } catch (error) {
        console.error('Error sending message:', error);
        res.status(500).send({
            code: 500,
            message: '发送失败'
        });
    }
});

// Token 密钥与过期时间
const ACCESS_SECRET = 'access_secret_key';
const REFRESH_SECRET = 'refresh_secret_key';
const ACCESS_EXPIRE = '1m'; // Access Token 15 分钟过期
const REFRESH_EXPIRE = '7d'; // Refresh Token 7 天过期

// 生成 Token
const generateTokens = (user) => {
    const accessToken = jwt.sign({ id: user._id }, ACCESS_SECRET, { expiresIn: ACCESS_EXPIRE });
    const refreshToken = jwt.sign({ id: user._id }, REFRESH_SECRET, { expiresIn: REFRESH_EXPIRE });
    return { accessToken, refreshToken };
};

// 登录接口
router.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const user = await LoginModel.findOne({ username, password });

    if (!user) return res.status(401).send({ code: 401, msg: '用户名或密码错误' });

    const tokens = generateTokens(user);
    res.send({ code: 200, msg: '登录成功', ...tokens });
});

// 刷新 Token 接口
router.post('/refresh', async (req, res) => {
    const { refreshToken } = req.body;
    if (!refreshToken) return res.status(403).send({ code: 403, msg: '缺少 Refresh Token' });

    try {
        const decoded = jwt.verify(refreshToken, REFRESH_SECRET);
        const user = await LoginModel.findById(decoded._id);
        if (!user) return res.status(403).send({ code: 403, msg: '用户不存在' });

        const tokens = generateTokens(user);
        res.send({ code: 200, msg: '刷新成功', ...tokens });
    } catch (err) {
        return res.status(403).send({ code: 403, msg: 'Refresh Token 失效，请重新登录' });
    }
});

// 受保护接口
router.get('/getLogin', async (req, res) => {
    const authHeader = req.headers.authorization;
    if (!authHeader) return res.status(401).send({ code: 401, msg: '未提供 Token' });

    const token = authHeader.split(' ')[1];
    try {
        jwt.verify(token, ACCESS_SECRET);
        let login = await LoginModel.find();
        res.send({ code: 200, msg: '获取成功', login });
    } catch (err) {
        res.status(401).send({ code: 401, msg: 'Token 失效，请刷新' });
    }
});

router.post("/addRegister", (req, res) => {
    LoginModel.create(req.body)
    res.send({ code: 200, msg: '添加成功' })
})
module.exports = router;